package com.zhuoya.healthcard;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.blankj.utilcode.util.ToastUtils;
import com.epson.isv.eprinterdriver.Common.EpsStatus;
import com.epson.isv.eprinterdriver.Ctrl.EPSetting;
import com.epson.isv.eprinterdriver.Ctrl.EPrintManager;
import com.epson.isv.eprinterdriver.Ctrl.IPrintListener;
import com.zhuoya.healthcard.contants.Contants;
import com.zhuoya.healthcard.util.HttpUtil;
import com.ldoublem.loadingviewlib.view.LVCircularZoom;
import com.zhuoya.healthcard.util.ToastUtil;

import static com.epson.isv.eprinterdriver.Common.ServiceIntent.QueryFinishFactor.UserCancel;
import static com.epson.isv.eprinterdriver.Common.ServiceIntent.StopFactor.PrintSuccess;
import static com.epson.isv.eprinterdriver.Common.ServiceIntent.StopFactor.PrinterErrorOccur;
import static com.epson.isv.eprinterdriver.Common.ServiceIntent.StopFactor.PrinterStopButton;

public class PrintActivity extends BaseActity implements IPrintListener {
    public static final int MSG_UPDATE_TEXT = 0;
    public static final int OP_HEAD_CLEANING = 3;
    public static final int OP_NOZZLE_CHECK = 2;
    public static final int OP_PAPER_FEED = 4;
    public static final int OP_PRINT = 1;
    public static final int OP_ZERO = 0;
    private String imagePath;
    private ImageView imageView;
    private LVCircularZoom mLoading;
    private TextView mTimeCount;
    String registrationId;
    TextView tvPntStatus;
    private CountDownTimer countDownTimer;
    private int opCode;


    @Override
    public void onCreate(final Bundle bundle) {
        super.onCreate(bundle);
        setContentView(R.layout.activity_print);
        initView();
        Intent intent = getIntent();
        opCode = intent.getIntExtra("opCode", 0);
        registrationId = intent.getStringExtra("registrationId");
        if (opCode == 0) {
            return;
        }
        EPrintManager.instance().addPrintListener(this);
        if (opCode == 1) {
            imagePath = intent.getStringExtra("imgUrl");
            if (imagePath != null) {
                EPrintManager.instance().startPrint();
            } else {
                tvPntStatus.setText("打印路径不能为空，请返回重试");
            }
        } else if (opCode == 2) {
            EPrintManager.instance().startNozzleCheck();
        } else if (opCode == 3) {
            EPrintManager.instance().startHeadCleaning();
        } else if (opCode == 4) {
            EPrintManager.instance().startPaperFeed();
        }

    }

    private void initView() {
        tvPntStatus = findViewById(R.id.textView15);
        mLoading = findViewById(R.id.loading);
        imageView = findViewById(R.id.imageView8);
        mLoading.setVisibility(View.VISIBLE);
        mLoading.startAnim();
        mTimeCount = findViewById(R.id.timeCount);
        findViewById(R.id.back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View view) {
                onBackPressed();
            }
        });
        findViewById(R.id.backTV).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View view) {
                onBackPressed();
            }
        });
    }


    @Override
    public void onCleaningTime(final int n) {

    }


    @Override
    public String onPageBegin(final int n) {
        return imagePath;
    }

    @Override
    public boolean onPageFinished(final int n) {
        return n <= EPSetting.instance().getTotalPages();
    }

    @Override
    public void onPrintAutoContinue() {

    }

    @Override
    public void onPrintBegin() {
        Log.d("onPrintBegin", "开始打印");
    }

    @Override
    public void onPrintFinished(int factor) {
        int errorCode = EPrintManager.instance().getStatus().getErrorCode();
        ToastUtils.showShort(errorCode+"");
        mLoading.setVisibility(View.INVISIBLE);
        switch (factor) {
            case PrintSuccess:
                tvPntStatus.setText("打印成功！");
                imageView.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.success));
                countDownTimer = new CountDownTimer(5000, 1000) {
                    @Override
                    public void onTick(long millisUntilFinished) {
                        tvPntStatus.setText((millisUntilFinished) / 1000 + "秒后自动返回首页");
                    }

                    @Override
                    public void onFinish() {
                        onBackPressed();
                    }
                };
                countDownTimer.start();
                break;


            case PrinterStopButton:
                break;

            case UserCancel:
                tvPntStatus.setText("打印取消！");
                break;

            case PrinterErrorOccur:
                tvPntStatus.setText("打印错误！");
                EPrintManager.instance().startHeadCleaning();
                break;

            default: {
                tvPntStatus.setText("打印错误！");
                break;
            }
        }
        if (factor != PrintSuccess) {
            imageView.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.print_error));
            new Thread(new Runnable() {
                @Override
                public void run() {
                    final JSONObject jsonObject = new JSONObject();
                    jsonObject.put("registrationId", registrationId);
                    HttpUtil.submitPostData(Contants.uri + "order/registrationRecall", jsonObject, "utf-8");
                }
            }).start();
        }

    }

    @Override
    public void onPrintPause(final int n, final int n2, final EpsStatus epsStatus) {
        tvPntStatus.setText("打印暂停");
        new Thread(new Runnable() {
            @Override
            public void run() {
                final JSONObject jsonObject = new JSONObject();
                jsonObject.put("registrationId", registrationId);
                HttpUtil.submitPostData(Contants.uri + "order/registrationRecall", jsonObject, "utf-8");
            }
        }).start();
    }

    @Override
    public void onPrintResume() {
        tvPntStatus.setText("打印继续");
    }


    @Override
    public void onBackPressed() {
        if (EPrintManager.instance().isPrintBusy()) {
            if (opCode == OP_PRINT) {
                new AlertDialog.Builder(this)
                        .setTitle("温馨提示")
                        .setMessage("打印机打印中")
                        .setPositiveButton("取消打印", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                tvPntStatus.setText("打印取消中，请稍后");
                                EPrintManager.instance().cancelPrint();
                                System.gc();
                                startActivity(new Intent(PrintActivity.this, MainActivity.class));
                            }
                        }).setNegativeButton("继续打印", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();

                    }
                })
                        .create().show();


            } else {
                new AlertDialog.Builder(this)
                        .setTitle("温馨提示")
                        .setMessage("打印机打印中，请耐心等待")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        })
                        .create().show();
            }

        } else {
            startActivity(new Intent(this, MainActivity.class));
        }


    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
    }


}
